package com.kele.oplog.service;

import com.kele.common.model.response.PageResult;
import com.kele.common.model.response.Result;
import com.kele.common.model.response.ResultObject;
import com.kele.model.oplog.BrowseLog;
import com.kele.oplog.dao.BrowseLogRepository;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;

@Service
public class BrowseLogService {

    @Autowired
    BrowseLogRepository browseLogRepository;

    @Autowired
    MongoTemplate mongoTemplate;

    public Result insert(BrowseLog browseLog){
        browseLogRepository.insert(browseLog);//万一保存失败怎么办？
        return Result.SUCCESS();
    }

    public Result update(String id,BrowseLog browseLog){
        Optional<BrowseLog> byId = browseLogRepository.findById(new ObjectId(id));
        if(byId.isPresent()){
            BrowseLog browseLog1 = byId.get();
            BeanUtils.copyProperties(browseLog,browseLog1,"id","browseTime");
            browseLog1.setBrowseTime(new Date());
            browseLogRepository.save(browseLog1);
        }
        return Result.SUCCESS();
    }

    public Result delete(String id){
        browseLogRepository.deleteById(new ObjectId(id));

        return Result.SUCCESS();
    }

    public ResultObject<BrowseLog> findById(String id) {
        Optional<BrowseLog> byId = browseLogRepository.findById(new ObjectId(id));
        if(byId.isPresent()){
            return new ResultObject<>(true,"1","success",byId.get());
        }
        return new ResultObject<>(false,"0","fail",null);
    }

    /**
     * @param pageNo
     * @param pageSize
     * @param searchMap
     {
          "goodsName":"华为",
          "priceMin":"1000",
          "priceMax":"3000",
          "brand":"华为",
          "sortField":"price",
          "sortOrder":"ASC"
      }
     * @return
     */
    public PageResult<BrowseLog> search(Integer pageNo, Integer pageSize, Map searchMap){

        Query query = new Query();
        String goodsName = (String)searchMap.get("goodsName");
        if(!StringUtils.isEmpty(goodsName)){
            Pattern pattern = Pattern.compile("^.*"+ goodsName +".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("goodsName").regex(pattern));
        }

        String  priceMin = (String)searchMap.get("priceMin");
        String  priceMax = (String)searchMap.get("priceMax");
        Double price_min = 0D;
        Double price_max = 99999999D;
        if(!StringUtils.isEmpty(priceMin) || !StringUtils.isEmpty(priceMax)){
            try {
                price_min = Double.parseDouble(priceMin);
            }catch (NumberFormatException e){}
            try {
                price_max = Double.parseDouble(priceMax);
            }catch (NumberFormatException e){}

            query.addCriteria(Criteria.where("price").gt(price_min).lte(price_max));
        }

        String brand = (String)searchMap.get("brand");
        if(!StringUtils.isEmpty(brand)) {
            query.addCriteria(Criteria.where("brand").is(brand));
        }

        long count = mongoTemplate.count(query, BrowseLog.class);

        //分页
        if(pageNo<1){
            pageNo = 1;
        }
        pageNo = pageNo -1;

        if(pageSize <0){
            pageSize = 5;
        }
        Pageable pageable = PageRequest.of(pageNo,pageSize);

        //排序
        Sort sort = null;
        String sortField = (String)searchMap.get("sortField");
        if(!StringUtils.isEmpty(sortField)) {
            Sort.Direction direction = Sort.Direction.DESC;
            String sortOrder = (String)searchMap.get("sortOrder");
            if(!StringUtils.isEmpty(sortOrder) && sortOrder.equals("ASC")){
                direction = Sort.Direction.ASC;
            }
            sort = Sort.by(direction, sortField);
        }
        if(sort!=null){
            query.with(sort);
        }

        List<BrowseLog> content = mongoTemplate.find(query.with(pageable), BrowseLog.class);

        return new PageResult<BrowseLog>(count,content);
    }

}
